package cn.bone.springDemo.test02.config;

import com.alibaba.druid.pool.DruidDataSource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import javax.sql.DataSource;
import java.sql.SQLException;

/**
 * Created by superbone on 2018/9/4.
 * 1. 导入相关依赖
 *      数据源,数据库驱动,spring-jdbc模块
 * 2. 配置数据源,JdbcTemplate
 * 3. 给方法加上@Transactional注解,表示当前方法是一个事务方法
 * 4. @EnableTransactionManagement,开启基于注解的事务管理
 * 5. 配置事务管理器来控制事务
 */
@Configuration
@ComponentScan("cn.bone.springDemo.test02")
@EnableTransactionManagement
public class TxConfig {

    @Bean
    public DataSource dataSource(){
        DruidDataSource dataSource = new DruidDataSource();
        dataSource.setUsername("root");
        dataSource.setPassword("Foxconn$bone");
        dataSource.setDriverClassName("com.mysql.cj.jdbc.Driver");
        dataSource.setUrl(" jdbc:mysql://118.178.225.7:3306/test?useUnicode=true&characterEncoding=UTF-8&useSSL=false&serverTimezone=UTC");
        dataSource.setInitialSize(1);
        dataSource.setMinIdle(1);
        dataSource.setMaxActive(10);
        dataSource.setMaxWait(60000);
//        try {
            //此处不需要手动调用init方法.加载时会自动调用
//            dataSource.init();
//        } catch (SQLException e) {
//            e.printStackTrace();
//        }
        return dataSource;
    }

    @Bean
    public JdbcTemplate jdbcTemplate(){
        JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource());
        return jdbcTemplate;
    }


    //注册事务管理器
    @Bean
    public PlatformTransactionManager transactionManager(){
        return new DataSourceTransactionManager(dataSource());
    }
}
